<?php

namespace app\educational\controller;

use app\classes\model\ClassModel;
use app\course\model\CourseAdjustModel;
use app\course\model\CourseScheduleModel;
use app\educational\service\HolidayService;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;
use think\Log;


class HolidayController extends AdminBaseController
{
    public function index()
    {
//        //TODO:权限限制(管理员必须对应学校)
//        $uid = cmf_get_current_admin_id();
//        $class_mdl = new ClassModel();
//        $roles = $class_mdl->roleAuth($uid,$this->admin_shop_id);
//        if(count($roles)>0){
//            foreach($roles as $v){
//                if($v['name'] == '班主任'){
//                    $where['cl.header_master_id'] = ['=', $uid];//班主任
//                    break;
//                }
//            }
//        }
//
//        $school_id = 32;
//        $this->assign('school_id',$school_id);

        return $this->fetch();

    }

    public function batchHoliday()
    {
        //英文星期
        $en_week = [
            1 => 'monday',
            2 => 'tuesday',
            3 => 'wednesday',
            4 => 'thursday',
            5 => 'friday',
            6 => 'saturday',
            7 => 'sunday',
        ];

        $search_days = [6, 7];
        $search_days_total = count($search_days);

        $current_date = time();
        $name = '休息日';

        $start_year = ('2017');
        $end_year = ('2017');

        //开始年份
        $start = $start_year . '-01-01 00:00:00';
        $start_year_timestamp = strtotime($start);
        //结束年份
        $end = $end_year . '-12-31 23:59:59';
        $end_year_timestamp = strtotime($end);

        $result_timestamp = $end_year_timestamp - $start_year_timestamp;
        //年份间的总天数
        $all_days_total = ceil($result_timestamp / (24 * 60 * 60));
        //年份间的总周数
        $all_weeks_total = ceil($all_days_total / 7);
        //开始年份第一天是周几
        $start_week = date('N', $start_year_timestamp);

        //第一周的日期
        $key = array_search($start_week, $search_days);
        $left_search_days = array_slice($search_days, $key);

        $left_days_total = count($left_search_days);
        for ($i = 0; $i < $left_days_total; $i++) {
            $cur_day = date('Y-m-d', strtotime('this week ' . $en_week[$left_search_days[$i]] . '', $start_year_timestamp));
            $check_year = date('Y', strtotime('this week ' . $en_week[$left_search_days[$i]] . '', $start_year_timestamp));

            $data = [
                'shop_id' => $this->admin_shop_id,
                'date' => $cur_day,
                'name' => $name,
                'cur_year' => $check_year,
                'create_time' => $current_date,
            ];
            $holidays[] = $data;
        }

        //从第二周开始
        for ($i = 1; $i < $all_weeks_total; $i++) {
            if ($start_week == 7) {
                $day = $i * 7 - 1;
            } else {
                $day = $i * 7;
            }
            $date_timestamp = strtotime("+$day days", $start_year_timestamp);

            for ($j = 0; $j < $search_days_total; $j++) {
                $cur_day1 = date('Y-m-d', strtotime('this week ' . $en_week[$search_days[$j]] . '', $date_timestamp));
                $check_year1 = date('Y', strtotime('this week ' . $en_week[$search_days[$j]] . '', $date_timestamp));
                if ($check_year1 > $end_year) {
                    //超出结束年份
                    break;
                }
                $data = [
                    'shop_id' => $this->admin_shop_id,
                    'date' => $cur_day1,
                    'name' => $name,
                    'cur_year' => $check_year1,
                    'create_time' => $current_date,
                ];
                array_merge($holidays, $data);
            }
        }

//        var_dump($holidays);exit;
    }

    /**
     * 获取假期
     * @return \think\response\Json
     */
    public function ajaxGetHoliday()
    {
        $json_data = [];
        $param = $this->request->param();
        $year = $param['year'];
        if (empty($year) || !is_numeric($year)) {
            $year = date('Y');
        }

        $holiday = Db::name('holiday')->field(['id', 'name', 'date'])
            ->where('shop_id', '=', $this->admin_shop_id)
            ->where('cur_year', '=', $year)
            ->order('date', 'asc')
            ->select();

        if (count($holiday) > 0) {
            $holiday->toArray();
            foreach ($holiday as $v) {
                $v = [
                    'Id' => $v['id'],
                    'Name' => $v['name'],
                    'Date' => date('Y-m-d', $v['date'])
                ];
                array_push($json_data, $v);
            }

        }
        return json($json_data);
    }

    /**
     * 批量设置假期
     * @return \think\response\Json
     */
    public function ajaxBatchHolidays()
    {
        $handle_result = true;//默认处理成功
        //今日时间
        $init_date = date('Y-m-d 23:59:59');
        $today_timestamp = strtotime($init_date);
        $cur_time = time();
        $schedule_mdl = new CourseScheduleModel();//排课模型

        $param = $this->request->param();
        //假期
        $holidays = str_replace("'", '"', $param['Data']);
        $holidays = json_decode($holidays, true);
        //年份
        $year = str_replace("'", '"', $param['Year']);
        $year = json_decode($year, true);

        if (count($holidays) < 1) {
            $json_data = [
                'Message' => '请选择假期',
                'Status' => 0,
            ];
            return json($json_data);
        } else {
            Db::startTrans();
            try{
                //更新或新建假期
                foreach ($holidays as $k => $item) {
                    foreach ($item as $key => $val) {
                        //获取假期
                        $result = Db::name('holiday')
                            ->where('shop_id', '=', $this->admin_shop_id)
                            ->where('cur_year', '=', $year[$k])
                            ->where('date', '=', strtotime($val['Date']))
                            ->find();
                        if (count($result) > 0) {
                            //修改了假期的名称
                            if ($result['name'] != trim($val['Name'])) {
                                //更新
                                $new_data = [
                                    'name' => trim($val['Name']),
                                ];
                                Db::name('holiday')
                                    ->where('shop_id', '=', $this->admin_shop_id)
                                    ->where('cur_year', '=', $year[$k])
                                    ->where('date', '=', strtotime($val['Date']))
                                    ->update($new_data);
                            }
                        } else {
                            //新建
                            $new_data = [
                                'shop_id' => $this->admin_shop_id,
                                'name' => trim($val['Name']),
                                'date' => strtotime($val['Date']),
                                'cur_year' => $year[$k],
                                'create_time' => $cur_time,
                            ];
                            Db::name('holiday')->insert($new_data);
                        }
                    }
                }
                //重新排课
                $res = $schedule_mdl->reSchedules($today_timestamp,$this->admin_shop_id);
                if(!$res){
                    //手动抛出异常
                    \exception('重新排课失败');
                    $handle_result = false;
                }

                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $handle_result = false;
            }
        }

        if(!$handle_result){
            $json_data = [
                'Message' => '批量设置假期重新排课失败',
                'Status' => 0,
            ];
            return json($json_data);
        }
        //记录日志
        $pk = 0;
        $table = 'holiday,course_schedule';
        $content = lang('SET_HOLIDAY', ['year' => implode(',', $year)]);
        do_log($content, $pk, $table, $cur_time);

        $json_data = [
            'Message' => '操作成功',
            'Status' => 1,
        ];
        return json($json_data);
    }

    /**
     * 设置假期
     * @return \think\response\Json
     */
    public function ajaxAddHoliday()
    {
        $msg = '假期变动重新排课失败';
        $handle_result = true;//默认处理成功
        $new_timestamp = 0;//新设置的假期中大于今天的日期
        //今日时间
        $init_date = date('Y-m-d 23:59:59');
        $today_timestamp = strtotime($init_date);
        $cur_time = time();//当前时间
        $schedule_mdl = new CourseScheduleModel();//排课模型

        $param = $this->request->param();
        //年份
        $year = $param['Year'];

        //假期
        $holidays = str_replace("'", '"', $param['Data']);
        $holidays = json_decode($holidays, true);
        if (count($holidays) < 1) {
            //删除一年的假期
            Db::name('holiday')
                ->where('shop_id', '=', $this->admin_shop_id)
                ->where('cur_year', '=', $year)
                ->delete();
            //重新排课
            $res = $schedule_mdl->reSchedules($today_timestamp,$this->admin_shop_id,$msg);
            if(!$res){
                $json_data = [
                    'Message' => $msg,
                    'Status' => 0,
                ];
                return json($json_data);
            }

        } else {
            //获取日期值
            $dates = array_column($holidays, 'Date');
            foreach ($dates as $k => $v) {
                $dates[$k] = strtotime($v);
            }

            //今天日期的时间戳
            $timestamp = strtotime(date('Y-m-d'));
            //查看今天是否是假期
            $today_holiday = Db::name('holiday')
                ->where('cur_year', '=', $year)
                ->where('date', '=', $timestamp)
                ->find();
            if(in_array($timestamp,$dates) && count($today_holiday)<=0){
                $json_data = [
                    'Message' => '不能设置当天为假期',
                    'Status' => 0,
                ];
                return json($json_data);
            }

            //获取年内大于今天的假期
            $old_holiday = Db::name('holiday')
                ->where('shop_id', '=', $this->admin_shop_id)
                ->where('cur_year', '=', $year)
                ->where('date', '>', $today_timestamp)
                ->group('date')
                ->select();
            if(!$old_holiday->isEmpty()){
                $old_holiday = $old_holiday->toArray();
                $old_dates = array_column($old_holiday,'date');
            }else{
                $old_dates = [];
            }

            //循环处理假期和重新排课
            Db::startTrans();
            try{
                //被删除的假期
                $delete_data = Db::name('holiday')
                    ->where('shop_id', '=', $this->admin_shop_id)
                    ->where('cur_year', '=', $year)
                    ->whereNotIn('date', $dates)
                    ->select();
                if (count($delete_data) > 0) {
                    $new_delete_data = $delete_data->toArray();
                    $ids = array_column($new_delete_data, 'id');
                    //删除假期
                    Db::name('holiday')->delete($ids);

                }

                //循环新建或更新假期
                foreach ($holidays as $val) {
                    //获取假期
                    $result = Db::name('holiday')
                        ->where('shop_id', '=', $this->admin_shop_id)
                        ->where('cur_year', '=', $year)
                        ->where('date', '=', strtotime($val['Date']))
                        ->find();
                    if (count($result) > 0) {
                        //修改了假期的名称
                        if ($result['name'] != trim($val['Name'])) {
                            //更新
                            $new_data = [
                                'name' => trim($val['Name']),
                            ];
                            Db::name('holiday')
                                ->where('shop_id', '=', $this->admin_shop_id)
                                ->where('cur_year', '=', $year)
                                ->where('date', '=', strtotime($val['Date']))
                                ->update($new_data);
                        }
                    } else {
                        //新建
                        $new_data = [
                            'shop_id' => $this->admin_shop_id,
                            'name' => trim($val['Name']),
                            'date' => strtotime($val['Date']),
                            'cur_year' => $year,
                            'create_time' => $cur_time,
                        ];
                        Db::name('holiday')->insert($new_data);
                    }
                }

                //合并假期，并去除重复数据
                $new_dates = array_merge($dates, $old_dates);
                $new_dates = array_unique($new_dates);

                //对日期升序排列
                sort($new_dates);
                foreach ($new_dates as $k=>$v){
                    if($v > $today_timestamp){
                        //新设置的假期中大于今天的日期
                        $new_timestamp = $v;
                        break;
                    }
                }

                //只有今日后存在要处理的假期才重排课
                if($new_timestamp > $today_timestamp){
                    //重新排课
                    $res = $schedule_mdl->reSchedules($new_timestamp,$this->admin_shop_id,$msg);
                    if(!$res){
                        //手动抛出异常
                        \exception('重新排课失败');
                        $handle_result = false;
                    }
                }

                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $handle_result = false;
            }
        }

        if(!$handle_result){
            $json_data = [
                'Message' => $msg,
                'Status' => 0,
            ];
            return json($json_data);
        }

        //记录日志
        $pk = 0;
        $table = 'holiday,course_schedule';
        $content = lang('SET_HOLIDAY', ['year' => $year]);
        do_log($content, $pk, $table, $cur_time);

        $json_data = [
            'Message' => '操作成功',
            'Status' => 1,
        ];
        return json($json_data);
    }

}